<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
      svg{
        background-color: #eeee;
      }
    </style>
</head>
<body>
    <svg id="svg"></svg>
</body>
</html>
<script src="http://d3js.org/d3.v6.min.js"></script>
<script>
  let width = 600,height=400,offset=50;
let svg = d3.select('#svg').attr('width',width).attr('height',height);
let g = svg.append('g');
let data = [10,23,32,34,54,42,21,15,19];




// 创建 x 比例尺
console.log(d3.range(data.length))
let xScale = d3.scaleBand().domain(d3.range(data.length)).range([0,width-offset*2])
// 创造x轴
let xAxis = d3.axisBottom(xScale)
g.append('g').call(xAxis).attr(`transform`,`translate(${offset},${height-offset})`)

// 创建 y 比例尺
let yScale = d3.scaleLinear().domain([0,d3.max(data)+20]).range([height - offset*2,0])
// .nice()
// 创造y轴
let yAxis = d3.axisLeft(yScale)
g.append('g').call(yAxis).attr(`transform`,`translate(${offset},${offset})`)


// 创造线
let line = d3.line().x(function(d,i){
  return xScale(i) + offset + (width-offset*2)/data.length/2
}).y(function(d,i){
  return yScale(d) + offset
})
// .curve(d3.curveCatmullRom )
// console.log(line(data),data)
g.append('path').attr('d',line(data)).attr('stroke','#333').attr('fill','none').attr('stroke-width',3)
.attr('stroke','blue').attr('stroke-dasharray', 5)


// 线上的点
g.append('g').selectAll('circle').data(data).enter()
.append('circle')
.attr('cx',function(d,i){
  return xScale(i) + offset + (width-offset*2)/data.length/2
})
.attr('cy',function(d,i){
  return yScale(d) + offset
})
.attr('r',6)
.attr('fill','blue')

// 线上的字
g.append('g').selectAll('text').data(data).enter()
.append('text')
.attr('x',function(d,i){
  return xScale(i) + offset + (width-offset*2)/data.length/2
})
.attr('y',function(d,i){
  return yScale(d) + offset - 10
})
.attr('text-anchor','middle')
.text(function(d,i){
  return d
})


</script>